<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: rgb(98, 159, 184);
            overflow: hidden;
            position: absolute;
            left: 100px;
            top: 100px;
        }

        .active {
            z-index: 999;
        }
    </style>
</head>

<body>
    <button class="back">back</button>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
<script>

    // 利用class类

    class Drag {
        constructor(ele) {
            this.target = ele;
            this.init();
        }
        init() {
            this.randColor();
            this.dragStart();
        }
        dragStart() {
            this.target.onmousedown = (e) => {
                var e = e || window.event;

                var posX = e.offsetX;
                var posY = e.offsetY;
                this.posX = posX;
                this.posY = posY;

                this.target.classList.add("active");

                this.dragMove()    // 先按下再移动
                this.dragEnd()     // 按下时绑定抬起                   

            }
        }
        dragMove() {
            document.onmousemove = (e) => {
                var e = e || window.event;

                var x = e.pageX - this.posX;
                var y = e.pageY - this.posY;
                this.target.style.left = x + "px";
                this.target.style.top = y + "px";

            }
        }
        dragEnd() {
            document.onmouseup = () => {
                var e = e || window.event;
                document.onmousemove = null;
                document.onmousedown = null;
                this.target.classList.remove("active")
            }
        }
        randColor() {
            this.target.style.backgroundColor = `rgb(${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)})`;
        }

    }

    console.dir(Drag);

    var boxList = document.getElementsByClassName("box");   // 拖拽的元素
    for (let i = 0; i < boxList.length; i++) {
        let box = boxList[i];
        let obj = new Drag(box);
        console.log(obj);
    }




</script>

</html>